import { DrawerForm, ProFormText } from '@ant-design/pro-components';
import { Button, Form } from 'antd';
import { useState } from 'react';
import api from './request';

export type FormConfig = { Component: any; props: Record<string, any> };
export interface Props {
  data?: MerchantManagerShopApi.AllListResponse;
  onSuccess?: () => void;
  onCancel?: () => void;
}
function MerchantManagerShopStatusForm(props: Props) {
  const { data } = props;

  const [form] = Form.useForm();
  const [formData, setFormData] = useState<any>({});
  const [info, setInfo] = useState<Partial<MerchantManagerShopApi.AllListResponse>>({});

  const onOpenChange = (open: boolean) => {
    if (open) {
      if (data && data.shopId) {
        setInfo(data);
        form.setFieldsValue(data);
        setFormData(data);
      }
    } else {
      setInfo({});
      form.resetFields();
      setFormData({});
      props.onCancel?.();
    }
  };
  const onSubmit = async () => {
    const { mobileno, verificationCode } = formData;
    const { shopId = '', shopName = '' } = info;

    const params: MerchantManagerShopApi.StatusParams = {
      mobileno,
      verificationCode,
      shopId,
      shopName,
    };
    const data = await api.updateStatus(params);
    if (data.success) props.onSuccess?.();
    return data.success;
  };

  return (
    <DrawerForm
      autoFocusFirstInput
      title={`核销券码`}
      form={form}
      drawerProps={{ destroyOnClose: true }}
      resize={{
        maxWidth: window.innerWidth * 0.8,
        minWidth: 400,
        onResize() {},
      }}
      trigger={<Button type="primary">核销券码</Button>}
      onOpenChange={onOpenChange}
      onFinish={onSubmit}
    >
      <ProFormText
        required
        name="mobileno"
        label="手机号"
        placeholder="请输入手机号"
        rules={[{ required: true }, { pattern: /^1\d{10}/, message: '请输入正确的手机号' }]}
        fieldProps={{
          value: formData.mobileno,
          onChange: (e) => setFormData({ ...formData, mobileno: e.target.value }),
        }}
      />
      <ProFormText
        required
        name="verificationCode"
        label="优惠券码"
        placeholder="请输入优惠券码"
        rules={[{ required: true }]}
        fieldProps={{
          value: formData.verificationCode,
          onChange: (e) => setFormData({ ...formData, verificationCode: e.target.value }),
        }}
      />
    </DrawerForm>
  );
}

export default MerchantManagerShopStatusForm;
